<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="预约日期" prop="visitDate">
        <el-date-picker clearable
          v-model="queryParams.visitDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择预约日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="预约时间" prop="visitTime">
        <el-date-picker clearable
          v-model="queryParams.visitTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择预约时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="联系人姓名" prop="contactName">
        <el-input
          v-model="queryParams.contactName"
          placeholder="请输入联系人姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input
          v-model="queryParams.contactPhone"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预约状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择预约状态" clearable>
          <el-option label="全部" value="" />
          <el-option label="待审批" value="0" />
          <el-option label="审批通过" value="1" />
          <el-option label="用户取消" value="2" />
          <el-option label="驳回" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:appointment:add']"
        >新增</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:appointment:edit']"
        >修改</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:appointment:remove']"
        >删除</el-button> 
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:appointment:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="appointmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="appointmentId" />
      <el-table-column label="仓库" align="center" prop="warehouse.warehouseName" />
      <el-table-column label="预约日期" align="center" prop="visitDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.visitDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预约时间" align="center" prop="visitTime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.visitTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="参观人数" align="center" prop="visitorCount" />
      <el-table-column label="联系人姓名" align="center" prop="contactName" />
      <el-table-column label="联系电话" align="center" prop="contactPhone" />
      <el-table-column label="电子邮箱" align="center" prop="email" />
      <el-table-column label="备注信息" align="center" prop="remarks" />
      <el-table-column label="预约状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="驳回原因" align="center" prop="rejectionReasons" width="150">
        <template slot-scope="scope">
          <span v-if="scope.row.status === '3' && scope.row.rejectionReasons" 
                :title="scope.row.rejectionReasons" 
                style="cursor: pointer; color: #f56c6c;">
            {{ scope.row.rejectionReasons.length > 20 ? scope.row.rejectionReasons.substring(0, 20) + '...' : scope.row.rejectionReasons }}
          </span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="申请人" align="center" prop="user.nikeName" /> -->
      <el-table-column v-if="status == '0'" label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <!-- 待审批状态显示审批按钮 -->
          <el-button
            v-if="scope.row.status == '0'"
            size="mini"
            type="success"
            icon="el-icon-check"
            @click="handleApprove(scope.row, '1')"
            v-hasPermi="['system:appointment:approve']"
          >通过</el-button>
          <el-button
            v-if="scope.row.status == '0'"
            size="mini"
            type="danger"
            icon="el-icon-close"
            @click="handleApprove(scope.row, '3')"
            v-hasPermi="['system:appointment:approve']"
          >驳回</el-button>
          <!-- 其他状态显示修改和删除按钮
          <el-button
            v-if="scope.row.status != '0'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:appointment:edit']"
          >修改</el-button>
          <el-button
            v-if="scope.row.status != '0'"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:appointment:remove']"
          >删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改仓库预约列表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
         <el-form-item label="园区" prop="parkId">
          <el-input v-model="form.parkId" placeholder="请输入园区ID" />
        </el-form-item>
        <el-form-item label="仓库" prop="warehouseId">
          <el-input v-model="form.warehouseId" placeholder="请输入仓库ID" />
        </el-form-item>
        <!-- <el-form-item label="预约日期" prop="visitDate">
          <el-date-picker clearable
            v-model="form.visitDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择预约日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预约时间" prop="visitTime">
          <el-date-picker clearable
            v-model="form.visitTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择预约时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="参观人数" prop="visitorCount">
          <el-input v-model="form.visitorCount" placeholder="请输入参观人数" />
        </el-form-item>
        <el-form-item label="联系人姓名" prop="contactName">
          <el-input v-model="form.contactName" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入电子邮箱" />
        </el-form-item>
        <el-form-item label="备注信息" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="审批时间" prop="approveTime">
          <el-date-picker clearable
            v-model="form.approveTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择审批时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审批人ID" prop="approveId">
          <el-input v-model="form.approveId" placeholder="请输入审批人ID" />
        </el-form-item>
        <el-form-item label="申请人ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入申请人ID" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 驳回原因输入对话框 -->
    <el-dialog title="驳回原因" :visible.sync="rejectDialogVisible" width="500px" append-to-body>
      <el-form ref="rejectForm" :model="rejectForm" :rules="rejectRules" label-width="80px">
        <el-form-item label="驳回原因" prop="rejectionReasons">
          <el-input
            v-model="rejectForm.rejectionReasons"
            type="textarea"
            :rows="4"
            placeholder="请输入驳回原因"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitReject">确 定</el-button>
        <el-button @click="cancelReject">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAppointment, getAppointment, delAppointment, addAppointment, updateAppointment } from "@/api/system/appointment"

export default {
  name: "Appointment",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 仓库预约列表表格数据
      appointmentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 驳回对话框显示状态
      rejectDialogVisible: false,
      // 驳回表单数据
      rejectForm: {
        appointmentId: null,
        rejectionReasons: '',
        status: '3'
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        warehouseId: null,
        visitDate: null,
        visitTime: null,
        contactName: null,
        contactPhone: null,
        email: null,
        status: "", // 默认选择"全部"状态
        userId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        warehouseId: [
          { required: true, message: "仓库ID不能为空", trigger: "blur" }
        ],
        visitDate: [
          { required: true, message: "预约日期不能为空", trigger: "blur" }
        ],
        visitTime: [
          { required: true, message: "预约时间不能为空", trigger: "blur" }
        ],
        visitorCount: [
          { required: true, message: "参观人数不能为空", trigger: "blur" }
        ],
        contactName: [
          { required: true, message: "联系人姓名不能为空", trigger: "blur" }
        ],
        contactPhone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" }
        ],
        email: [
          { required: true, message: "电子邮箱不能为空", trigger: "blur" }
        ],
      },
      // 驳回表单校验
      rejectRules: {
        rejectionReasons: [
          { required: true, message: "驳回原因不能为空", trigger: "blur" },
          { min: 1, max: 500, message: "驳回原因长度在 1 到 500 个字符", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询仓库预约列表列表 */
    getList() {
      this.loading = true
      listAppointment(this.queryParams).then(response => {
        this.appointmentList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        appointmentId: null,
        warehouseId: null,
        visitDate: null,
        visitTime: null,
        visitorCount: null,
        contactName: null,
        contactPhone: null,
        email: null,
        remarks: null,
        status: null,
        createTime: null,
        updateTime: null,
        approveTime: null,
        approveId: null,
        userId: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      // 如果状态为空字符串，则不传递该参数
      if (this.queryParams.status === '') {
        this.queryParams.status = null
      }
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      // 重置后设置状态为"全部"
      this.queryParams.status = ""
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.appointmentId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加仓库预约列表"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const appointmentId = row.appointmentId || this.ids
      getAppointment(appointmentId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改仓库预约列表"
      })
    },
    /** 审批操作 */
    handleApprove(row, status) {
      if (status === '3') {
        // 驳回时需要输入驳回原因
        this.rejectForm.appointmentId = row.appointmentId
        this.rejectForm.rejectionReasons = ''
        this.rejectDialogVisible = true
      } else {
        // 直接通过审批
        this.submitApprove(row.appointmentId, status, '')
      }
    },
    /** 提交审批 */
    submitApprove(appointmentId, status, rejectionReasons = '') {
      const data = {
        appointmentId: appointmentId,
        status: status,
        rejectionReasons: rejectionReasons,
        approveId: this.$store.getters.userId, // 获取当前登录用户ID作为审批人
        approveTime: new Date().toISOString()
      }
      
      updateAppointment(data).then(response => {
        this.$modal.msgSuccess(status === '1' ? "审批通过成功" : "驳回成功")
        this.rejectDialogVisible = false
        this.getList()
      })
    },
    /** 提交驳回 */
    submitReject() {
      this.$refs["rejectForm"].validate(valid => {
        if (valid) {
          this.submitApprove(this.rejectForm.appointmentId, '3', this.rejectForm.rejectionReasons)
        }
      })
    },
    /** 取消驳回 */
    cancelReject() {
      this.rejectDialogVisible = false
      this.rejectForm.rejectionReasons = ''
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.appointmentId != null) {
            updateAppointment(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addAppointment(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const appointmentIds = row.appointmentId || this.ids
      this.$modal.confirm('是否确认删除仓库预约列表编号为"' + appointmentIds + '"的数据项？').then(function() {
        return delAppointment(appointmentIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/appointment/export', {
        ...this.queryParams
      }, `appointment_${new Date().getTime()}.xlsx`)
    },
    /** 获取状态类型 */
    getStatusType(status) {
      const statusMap = {
        '0': 'warning',   // 待审批 - 黄色
        '1': 'success',   // 审批通过 - 绿色
        '2': 'info',      // 用户取消 - 蓝色
        '3': 'danger'     // 驳回 - 红色
      }
      return statusMap[status] || 'info'
    },
    /** 获取状态文本 */
    getStatusText(status) {
      const statusMap = {
        '0': '待审批',
        '1': '审批通过',
        '2': '用户取消',
        '3': '驳回'
      }
      return statusMap[status] || '未知状态'
    }
  }
}
</script>
